﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace SimpleUnitity.Log
{
    public enum PerTimeType
    {
        Year,
        Month,
        Week,
        Day,
        Hour,
        Minute,
        Second
    }

    public class PerTimeFileLog : ILog
    {
        private readonly string filepath;
        PerTimeType pertype;
        private string filenameformat = "yyyyMMddss";

        public PerTimeFileLog(string logfilepath, PerTimeType pertype)
        {
            logfilepath = logfilepath.Replace('\\', '/');
            if (logfilepath.Length > 0 && logfilepath.EndsWith("/") == false)
            {
                logfilepath += "/";
            }
            if (Directory.Exists(logfilepath) == false)
            {
                Directory.CreateDirectory(logfilepath);
            }
            this.filepath = logfilepath;
            this.pertype = pertype;
            switch (pertype)
            {
                case PerTimeType.Year: filenameformat = "yyyy"; break;
                case PerTimeType.Month: filenameformat = "yyyyMM"; break;
                case PerTimeType.Week: filenameformat = "yyyyMMdd"; break;
                case PerTimeType.Day: filenameformat = "yyyyMMdd"; break;
                case PerTimeType.Hour: filenameformat = "yyyyMMddHH"; break;
                case PerTimeType.Minute: filenameformat = "yyyyMMddmm"; break;
                case PerTimeType.Second: filenameformat = "yyyyMMddss"; break;
            }
        }

        readonly object syncObject = new object();
        public void Write(string message, ELogLevel level)
        {
            DateTime now = DateTime.Now;
            if (pertype == PerTimeType.Week)
            {
                now = now.AddDays((int)now.DayOfWeek);
            }
            string filename = string.Format("{0}{1}.log", filepath, now.ToString(filenameformat));
            lock (syncObject)
            {
                string contents = string.Format("{0:yyyy-MM-dd HH:mm:ss}\t{1}\t{2}{3}", DateTime.Now, level, message, Environment.NewLine);
                try
                {
                    File.AppendAllText(filename, contents);
                }
                catch
                {
                    string path = filename.Substring(0, filename.Replace('\\', '/').LastIndexOf("/"));
                    Directory.CreateDirectory(path);
                    File.AppendAllText(filename, contents);
                }
            }
        }
    }
}
